package com.coinbixin.ui.quick_purchase;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListPopupWindow;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.coinbixin.ui.home.MainActivity;
import com.coinbixin.ui.setting.GongGaoActivity;
import com.coinbixin.utils.WonderfulToastUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gyf.barlibrary.ImmersionBar;
import com.coinbixin.R;
import com.coinbixin.ui.message_detail.MessageDetailActivity;
import com.coinbixin.adapter.GongGaoAdapter;
import com.coinbixin.base.BaseActivity;
import com.coinbixin.base.LinListView;
import com.coinbixin.app.UrlFactory;
import com.coinbixin.utils.WonderfulLogUtils;
import com.coinbixin.utils.okhttp.StringCallback;
import com.coinbixin.utils.okhttp.WonderfulOkhttpUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Request;

import static com.coinbixin.utils.WonderfulDpPxUtils.dip2px;

/**
 * Created by Administrator on 2018/8/9.
 */
public class BuyItemPricesActivity extends BaseActivity {
    @BindView(R.id.tv_item_price)
    TextView tv_item_price;
    @BindView(R.id.et_buy_item_num)
    EditText et_buy_item_num;
    @BindView(R.id.ll_buy_item_setting)
    LinearLayout ll_buy_item_setting;
    @BindView(R.id.tv_buy_total)
    TextView tv_buy_total;
    @BindView(R.id.tv_select_bank_name)
    TextView tv_select_bank_name;
    @BindView(R.id.ll_buy_button)
    LinearLayout ll_buy_button;
    @BindView(R.id.quickbuy_ibBack)
    ImageButton quickbuy_ibBack;
    @BindView(R.id.iv_image_arrow)
    ImageView iv_image_arrow;
    @BindView(R.id.ll_select_purchase_type)
    LinearLayout ll_select_purchase_type;
    @BindView(R.id.ll_prices_main)
    LinearLayout ll_prices_main;
    private SortAadapter adapter = null;
    private ListPopupWindow listPopupWindow = null;
    private UIHandler mHandler = new UIHandler();
    private Thread mThread;
    private boolean flag = true;

    private class SortAadapter extends ArrayAdapter {

        private String[] strs = getResources().getStringArray(R.array.ctc_payType);
        private LayoutInflater inflater;
        private int res;

        public SortAadapter(Context context, int resource) {
            super(context, resource);
            inflater = LayoutInflater.from(context);
            res = resource;
        }

        public View getView(int position, View convertView) {
            if (convertView == null)
                convertView = inflater.inflate(res, null);

            TextView text = (TextView) convertView.findViewById(android.R.id.text1);
            text.setText(getItem(position));
            text.setTextColor(getResources().getColor(R.color.white));
            text.setTextSize(10);

            convertView.setBackgroundColor(getResources().getColor(R.color.bg_kline_bottom));
            convertView.setAlpha(0);

            return convertView;
        }

        @Override
        public String getItem(int position) {
            return strs[0];
        }

        @Override
        public int getCount() {
            //return strs.length;
            return 1;
        }
    }

    private class UIHandler extends Handler {
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            if(msg.what==1) {
                //et_buy_item_num.setFocusable(false);
                if(!et_buy_item_num.getText().toString().equals("")) {
                    int number = Integer.parseInt(et_buy_item_num.getText().toString());
                    float prices = Float.parseFloat(tv_item_price.getText().toString());
                    float total = number * prices;
                    tv_buy_total.setText(String.format("%10.2f",total));
                }
            }
        }
    }

    public void showListPopupWindow(View view) {
        if (listPopupWindow == null)
            listPopupWindow = new ListPopupWindow(this);

        if (adapter == null) {
            adapter = new SortAadapter(this, android.R.layout.simple_list_item_1);

            // ListView适配器
            listPopupWindow.setAdapter(adapter);

            // 选择item的监听事件
            listPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
                    Toast.makeText(getApplicationContext(), adapter.getItem(pos), Toast.LENGTH_SHORT).show();
                    tv_select_bank_name.setText(adapter.getItem(pos));

                    listPopupWindow.dismiss();
                }
            });

            listPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    //旋转0度是复位ImageView
                    iv_image_arrow.animate().setDuration(500).rotation(0).start();
                }
            });
        }


        // ListPopupWindow的锚,弹出框的位置是相对当前View的位置
        listPopupWindow.setAnchorView(view);

        listPopupWindow.setVerticalOffset(dip2px(this,5));

        // 对话框的宽高
        listPopupWindow.setWidth(view.getWidth());

        listPopupWindow.setModal(true);

        listPopupWindow.show();
        iv_image_arrow.animate().setDuration(500).rotation(180).start();
    }

    @Override
    protected int getActivityLayoutId() {
        return R.layout.activity_buy_item_prices;
    }
    public static void actionStart(Activity context) {
        Intent intent = new Intent(context, BuyItemPricesActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        flag=true;
        Thread mThread2 = new Thread(new Runnable()
        {
            @Override
            public void run() {
                int i=0;
                while(flag)
                {
                    android.os.Message msg = new Message();
                    msg.what=1;
                    mHandler.sendMessage(msg);
                    try {
                        Thread.sleep(500);
                    }catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        mThread2.start();
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {

        mThread = new Thread(new Runnable()
        {
            @Override
            public void run() {
                int i=0;
                while(flag)
                {
                    android.os.Message msg = new Message();
                    msg.what=1;
                    mHandler.sendMessage(msg);
                    try {
                        Thread.sleep(500);
                    }catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        mThread.start();

      ll_buy_button.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              if(!et_buy_item_num.getText().toString().equals("")) {
                  int number = Integer.parseInt(et_buy_item_num.getText().toString());
                  float prices = Float.parseFloat(tv_item_price.getText().toString());
                  float total = Float.parseFloat(tv_buy_total.getText().toString());
                  byte pay_id=0;

                  if (number == 0) {
                      Toast.makeText(getApplicationContext(), R.string.warning_num_tips, Toast.LENGTH_SHORT).show();
                  } else {
                      String which_pay = tv_select_bank_name.getText().toString();
                      String[] titles=getResources().getStringArray(R.array.ctc_payType);
                      if(which_pay.equals(titles[0]))
                      {
                          pay_id = 0;
                      }else{
                          pay_id=3;
                      }

                      if(pay_id!=3)
                      {
                          //BuyBillDetailActivity.actionStart(BuyItemPricesActivity.this,prices,pay_id,number,total);
                          new AlertDialog.Builder(BuyItemPricesActivity.this, R.style.custom_dialog)
                                  .setIcon(null)
                                  .setMessage(getResources().getText(R.string.item_buy_warning))
                                  .setPositiveButton(getResources().getText(R.string.buy_sure), new DialogInterface.OnClickListener() {

                                      @Override
                                      public void onClick(DialogInterface dialog, int which) {
                                          flag=false;
                                          int number1 = Integer.parseInt(et_buy_item_num.getText().toString());
                                          float prices1 = Float.parseFloat(tv_item_price.getText().toString());
                                          float total1 = Float.parseFloat(tv_buy_total.getText().toString());
                                          byte pay_id = 0;
                                          BuyBillDetailActivity.actionStart(BuyItemPricesActivity.this,prices1,pay_id,number1,total1);
                                      }
                                  })
                                  .setNegativeButton(getResources().getText(R.string.buy_think), new DialogInterface.OnClickListener() {
                                      @Override
                                      public void onClick(DialogInterface dialog, int which) {
                                          flag=false;
                                          dialog.dismiss();
                                          finish();
                                      }
                                  })
                                  .show().setCancelable(false);
                      }else{
                          Toast.makeText(getApplicationContext(),R.string.warning_pay_tips, Toast.LENGTH_SHORT).show();
                      }
                  }
              }else{
                  Toast.makeText(getApplicationContext(), R.string.warning_num_pay_tips, Toast.LENGTH_SHORT).show();
              }

            //finish();
          }
      });

      ll_prices_main.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
//              et_buy_item_num.setFocusable(false);
//              if(!et_buy_item_num.getText().toString().equals("")) {
//                  int number = Integer.parseInt(et_buy_item_num.getText().toString());
//                  float prices = Float.parseFloat(tv_item_price.getText().toString());
//                  float total = number * prices;
//                  tv_buy_total.setText(String.format("%10.2f",total));
//              }

          }
      });

    ll_select_purchase_type.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showListPopupWindow(ll_select_purchase_type);
        }
    });

      quickbuy_ibBack.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              flag=false;
              finish();
          }
      });

      et_buy_item_num.setOnFocusChangeListener(new View.OnFocusChangeListener() {
          @Override
          public void onFocusChange(View v, boolean hasFocus) {
              if(hasFocus){

              }else{

              }
          }
      });

      et_buy_item_num.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              et_buy_item_num.setFocusable(true);
              et_buy_item_num.setFocusableInTouchMode(true);
              et_buy_item_num.requestFocus();
              et_buy_item_num.findFocus();
          }
      });

    }

    @Override
    protected void obtainData() {

    }

    @Override
    protected void fillWidget() {

    }

    @Override
    protected void loadData() {
        displayLoadingPopup();
        getMessage();
    }

    private void getMessage() {
        WonderfulOkhttpUtils.post().url(UrlFactory.getExchangeRate())
                .build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                hideLoadingPopup();
            }

            @Override
            public void onResponse(String response) {
                WonderfulLogUtils.logi("miao",response);
                hideLoadingPopup();
                try {
                    JSONObject object = new JSONObject(response);
                    if (object.optInt("data") == 0) {
                        JSONObject jsonObject =  object.getJSONObject("data");
                        float fValue = (float) jsonObject.getDouble("buy");
                        tv_item_price.setText(String.valueOf(fValue));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
            flag = false;
            return super.onKeyDown(keyCode, event);
        }else{
            return super.onKeyDown(keyCode, event);
        }

    }
}
